<template>
  <el-drawer v-model="drawerFlag" direction="rtl">
    <template #header>Roles</template>
    <template #default>
      <el-form :model="formModel" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="角色名称" prop="role_name">
          <el-input v-model="formModel.role_name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="role_description">
          <el-input type="textarea" v-model="formModel.role_description"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="handleClickBtnCancel">取消</el-button>
        <el-button type="primary" @click="handleClickBtnSubmit">提交</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { ref, reactive, defineEmits } from 'vue'
import Dal from '@/dal'
import { ElMessage } from 'element-plus'
import type { ElForm } from 'element-plus'

const drawerFlag = ref(false)

const emits = defineEmits(['close', 'submit'])

const formRef = ref<InstanceType<typeof ElForm>>()

const formModel = reactive({
  role_id: 0,
  role_name: '',
  role_description: '',
})
const rules = reactive({
  role_name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
})

const handleClickBtnCancel = () => {
  formRef.value?.resetFields()
  drawerFlag.value = false
}

const handleClickBtnSubmit = async () => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      // 这里可以添加提交表单数据到后端的逻辑

      const res = await Dal.Roles.save(formModel)
      console.log('表单数据：', formModel)
      console.log('res', res)
      // 假设提交成功后给用户提示
      ElMessage({
        message: '提交成功',
        type: 'success',
      })
      emits('submit', { ...formModel })
    } else {
      console.log('表单验证失败')
    }
  })

  drawerFlag.value = false
}

const open = () => {
  drawerFlag.value = true
  formModel.role_name = ''
  formModel.role_description = ''
}

defineExpose({
  open,
})
</script>
